package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.wxpay.sdk.Config;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.order.WeixinPayService;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinPayServiceImpl implements WeixinPayService {

    @Autowired
    private Config config;

    /**
     * 生成微信支付二维码
     *
     * @param orderId   订单号
     * @param money     金额(分)
     * @param notifyUrl 回调地址
     *
     * @param attach 附加参数，可有可无
     * @return
     */
    @Override
    public Map createNative(String orderId, Integer money, String notifyUrl,String... attach) {
        try {
            //1.配置请求的xml形式的参数
            Config config = new Config();
            Map<String,String> map = new HashMap<>();
            map.put("appid",config.getAppID());//公众账号ID
            map.put("mch_id",config.getMchID());//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            map.put("body","青橙");//商品描述
            map.put("out_trade_no",orderId);//商户订单号
            map.put("total_fee",money+"");//标价金额
            map.put("spbill_create_ip","127.0.0.1");//终端IP
            map.put("notify_url",notifyUrl);//通知地址
            map.put("trade_type","NATIVE");//交易类型

            //附加参数
            if(attach!=null&&attach.length>0){
                map.put("attach",attach[0]);
            }

            String xmlParam = WXPayUtil.generateSignedXml(map, config.getKey());//xml格式的参数
            System.out.println("参数:"+xmlParam);

            //2.发送请求
            WXPayRequest wxPayRequest = new WXPayRequest(config);
            String xmlResult = wxPayRequest.requestWithCert("/pay/unifiedorder", null, xmlParam, false);
            System.out.println("结果："+xmlResult);

            //3.解析返回结果
            Map<String,String> mapResult = WXPayUtil.xmlToMap(xmlResult);

            Map mapReturn = new HashMap();
            mapReturn.put("code_url",mapResult.get("code_url"));
            mapReturn.put("out_trade_no",orderId);
            mapReturn.put("total_fee",money+"");
            return mapReturn;
        } catch (Exception e) {
            e.printStackTrace();

            return new HashMap();
        }

    }

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 微信支付回调
     * @param xml
     */
    public void notifyLogic(String xml){

        try {
            //1.对xml解析 map
            Map<String,String> map = WXPayUtil.xmlToMap(xml);

            //2.验证签名
            boolean signatureValid = WXPayUtil.isSignatureValid(map, config.getKey());

            System.out.println("验证签名是否正确："+signatureValid);
            System.out.println(map.get("out_trade_no"));
            System.out.println(map.get("result_code"));

            //修改订单状态
            if(signatureValid){
                if("SUCCESS".equals(map.get("result_code"))){
                    orderService.updatePayStatus(map.get("out_trade_no"),map.get("transaction_id"));
                    // 发送消息，支付成功通知，返回订单id，与页面直接互相交互，webstock Stomp技术
                    rabbitTemplate.convertAndSend("paynotify","",map.get("out_trade_no"));
                }else{
                    //记录日志
                }
            }else{
                //记录日志
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询订单
     * @param orderId
     * @return
     */
    public boolean checkOrder(String orderId){

        boolean isSuccess=false;

        try {
            //1.配置请求的xml形式的参数
            Config config = new Config();
            Map<String,String> map = new HashMap<>();
            map.put("appid",config.getAppID());//公众账号ID
            map.put("mch_id",config.getMchID());//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            map.put("out_trade_no",orderId);//商户订单号

            String xmlParam = WXPayUtil.generateSignedXml(map, config.getKey());//xml格式的参数
            System.out.println("参数:"+xmlParam);

            //2.发送请求
            WXPayRequest wxPayRequest = new WXPayRequest(config);
            String xmlResult = wxPayRequest.requestWithCert("/pay/orderquery", null, xmlParam, false);
            System.out.println("结果："+xmlResult);

            //3.解析返回结果
            Map<String,String> mapResult = WXPayUtil.xmlToMap(xmlResult);

            if("SUCCESS".equals(mapResult.get("return_code"))){
                if("SUCCESS".equals(mapResult.get("result_code"))){ //查询交易状态是否为SUCCESS
                    isSuccess=true;
                }
            }else{
                isSuccess=false;
            }

            return  isSuccess;

        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }

    }


    /**
     * 关闭订单
     * @param orderId
     */
    public Map closeOrder(String orderId){

        try {
            //1.配置请求的xml形式的参数
            Config config = new Config();
            Map map = new HashMap();
            map.put("appid",config.getAppID());//公众账号ID
            map.put("mch_id",config.getMchID());//商户号
            map.put("nonce_str",WXPayUtil.generateNonceStr());//随机字符串
            map.put("out_trade_no",orderId);//商户订单号

            String xmlParam = WXPayUtil.generateSignedXml(map, config.getKey());//xml格式的参数
            System.out.println("参数："+xmlParam);

            //2.发送请求
            WXPayRequest wxPayRequest = new WXPayRequest(config);
            String xmlResult = wxPayRequest.requestWithCert("/pay/closeorder", "", xmlParam, false);
            System.out.println("结果："+xmlResult);

            //3.解析结果
            Map<String, String> mapResult = WXPayUtil.xmlToMap(xmlResult);

            return mapResult;//返回整个结果

        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }

    }
}
